<?php

declare(strict_types=1);

namespace xpzhu\Jwt\Middleware;

use Webman\Http\Response;
use Webman\Http\Request;
use Webman\MiddlewareInterface;
use xpzhu\Jwt\Exception\JwtException;
use xpzhu\Jwt\Facade\JwtAuth;

class JwtAuthMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        if ($request->method() === 'OPTIONS') {
            response('', 204);
        }

        try {
            JwtAuth::verify();
        } catch (JwtException $e) {
            throw new JwtException($e->getMessage(), $e->getCode());
        }

        $request->user = JwtAuth::getClaims();
        $request->uid  = JwtAuth::getClaim('id');

        // 已登录，请求继续穿越
        return $handler($request);
    }
}